/*
pub.cpp

Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2018 zjzengdongyang <http://zjzdy.cn>.

Permission is hereby  granted, free of charge, to any  person obtaining a copy
of this software and associated  documentation files (the "Software"), to deal
in the Software  without restriction, including without  limitation the rights
to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include <iostream>
#include "tmsg.hpp"

using namespace std;

int main(int argc, char* argv[])
{
    string serverURI;
    if(argc > 1)
        serverURI = argv[1];
    if(serverURI.empty())
        serverURI = "tcp://localhost:1883";
    tmsg tm(serverURI);//初始化tmsg
    //连接服务器
    if(!tm.connect()) {
        cout << "Connect fail." << endl;
        return -1;
    }
    cout << "Topic:";
    string topic;
    cin >> topic;
    string data;
    long long a = 0;
    //设置调试信息输出等级,默认不输出
    tm.setVerbose(4);
    while(1) {
        cout << a << ": ";
        cin >> data;//读取用户输入的待发送数据
        tmsg::msg m;
        m.pack("id", a++);//打包a进m里面, 这个数据的标识是id, 序号是0(因为是第一个被打包的数据),并将a后自增
        m.pack("data", data);//打包data进m里面, 这个数据的标识是data, 序号是1(因为是第二个被打包的数据)
        if(a%10 == 0)//隔10次消息, 再打包多一个数据,用于测试格式变动造成的影响
            m.pack("data2", 123456789);
        tm.publish(topic, m);//发布这个消息
    }
    return 0;
}